package middleware

import (
	"github.com/gin-gonic/gin"
	"go-malphite/app/common/resp"
	"go-malphite/app/common/state"
)

// Recover 捕获异常
func Recover(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			//封装通用json返回
			recoverErr(c, r)
			//终止后续接口调用，不加的话recover到异常后，还会继续执行接口里后续代码
			c.Abort()
		}
	}()
	//加载完 defer recover，继续后续接口调用
	c.Next()
}

// recover错误，转string
func recoverErr(c *gin.Context, r interface{}) {
	switch v := r.(type) {
	case error:
		resp.FailWithMsg(c, v.Error())
	case string:
		resp.FailWithMsg(c, v)
	case state.Exception:
		resp.FailWithCode(c, v)
	case state.Error:
		resp.FailWithCode(c, state.ServerBusy)
	default:
		resp.Fail(c)
	}
}
